package com.xhis.homenurse;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.xhis.homenurse.tools.DeviceInfo;
import com.xhis.homenurse.tools.DialogTools;
import com.xhis.homenurse.tools.RomUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 引导页
 * by 张兵 2019/6/28
 */
public class GuideActivity extends AppCompatActivity
{
    private ViewPager mViewPager;
    private int[] mImageIds = new int[]{R.mipmap.icon_guide_page1, R.mipmap.icon_guide_page2, R.mipmap.icon_guide_page3};
    private ArrayList<ImageView> mImageViewList;
    private LinearLayout llContainer;
    private ImageView ivRedPoint;
    private int mPaintDis;
    private Button start_btn;
    private TextView tvJump;
    private AlertDialog dialog;
    private boolean isFirst = true;// 判断是否第一次加载，第一次弹窗后置为false
    private String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA, Manifest.permission.ACCESS_COARSE_LOCATION
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    private List<String> mPermissionList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_guide);
        initView();
    }

    protected void initView()
    {
        mViewPager = (ViewPager) findViewById(R.id.guide_vp);
        llContainer = (LinearLayout) findViewById(R.id.guide_ll_container);
        ivRedPoint = (ImageView) findViewById(R.id.guide_iv_red);
        start_btn = (Button) findViewById(R.id.guide_start_btn);
        tvJump = (TextView) findViewById(R.id.guide_tv_jump);

        start_btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //点击进入的时候直接跳转到登录界面
                Intent intent = new Intent(GuideActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
        tvJump.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                //点击进入的时候直接跳转到登录界面
                Intent intent = new Intent(GuideActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });

        initData();
        GuideAdapter adapter = new GuideAdapter();
        //添加动画效果
//        mViewPager.setPageTransformer(true, new DepthPageTransformer());
        mViewPager.setAdapter(adapter);

        //监听布局是否已经完成  布局的位置是否已经确定
        ivRedPoint.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                //避免重复回调   出于兼容性考虑，使用了过时的方法
                ivRedPoint.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                //布局完成了就获取第一个小圆点和第二个之间left的距离
                mPaintDis = llContainer.getChildAt(1).getLeft() - llContainer.getChildAt(0).getLeft();
                System.out.println("距离：" + mPaintDis);
            }
        });

        //ViewPager滑动Pager监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            //滑动过程中的回调
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {
                //当滑到第二个Pager的时候，positionOffset百分比会变成0，position会变成1，所以后面要加上position*mPaintDis
                int letfMargin = (int) (mPaintDis * positionOffset) + position * mPaintDis;
                //在父布局控件中设置他的leftMargin边距
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivRedPoint.getLayoutParams();
                params.leftMargin = letfMargin;
                ivRedPoint.setLayoutParams(params);
            }

            /**
             * 设置按钮最后一页显示，其他页面隐藏
             */
            @Override
            public void onPageSelected(int position)
            {
                System.out.println("position:" + position);
                if (position == mImageViewList.size() - 1) {
                    ivRedPoint.setVisibility(View.GONE);
                    start_btn.setVisibility(View.VISIBLE);
                    tvJump.setVisibility(View.GONE);
                } else {
                    start_btn.setVisibility(View.GONE);
                    ivRedPoint.setVisibility(View.VISIBLE);
                    tvJump.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state)
            {
                System.out.println("state:" + state);
            }
        });
    }

    private boolean locationPermission()
    {
        AMapLocationClient mLocationClient = new AMapLocationClient(getApplicationContext());
        try {
//            LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//            // 无用操作
//            lm.getAllProviders();
            mLocationClient.startLocation();
            mLocationClient.stopLocation();
            return true;
        } catch (Exception e) {
            if (mLocationClient.isStarted()) {
                mLocationClient.stopLocation();
            }
            return false;
        }
    }

    private boolean cameraPermission()
    {
        Camera mCamera = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Field fieldPassword;
                if (mCamera == null) mCamera = Camera.open();
                //通过反射去拿相机是否获得了权限
                fieldPassword = mCamera.getClass().getDeclaredField("mHasPermission");
                fieldPassword.setAccessible(true);
                Boolean result = (Boolean) fieldPassword.get(mCamera);
                if (mCamera != null) {
                    mCamera.release();
                }
                mCamera = null;
                return result;
            }
        } catch (Exception e) {
            if (mCamera != null) {
                mCamera.release();
            }
            mCamera = null;
        }
        return true;
    }

    private boolean writePermission()
    {
        String absolute_dir;
        absolute_dir = Environment.getExternalStorageDirectory().toString() + "/xhisqxpd/";
        File f = new File(absolute_dir);
        try {
            if (!f.exists())
                f.mkdirs();
            if (f.exists()) {
                f.delete();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (f.exists()) {
                f.delete();
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        if (requestCode == 123) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(GuideActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        Toast.makeText(GuideActivity.this, "权限未申请", Toast.LENGTH_LONG).show();
                    } else {
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * api级别权限查询
     */
    private boolean selfPermissionGranted(String permission)
    {
        return PermissionChecker.checkSelfPermission(GuideActivity.this, permission) == PermissionChecker.PERMISSION_GRANTED;
    }

    /**
     * api级别权限查询 6.0之前
     */
    private boolean checkPermissionGranted(String permission)
    {
        return getPackageManager().checkPermission(permission, getPackageName()) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting()
    {
        dialog = new AlertDialog.Builder(this)
                .setTitle("部分权限不可用")
                .setCustomTitle(DialogTools.getDialgoTitleView(this, "部分权限不可用", R.mipmap.hintdialog))
                .setMessage("请在-应用设置-权限-中，打开相应权限，以保证应用正常使用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
//                        finish();
                    }
                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting()
    {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 321);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == 321) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                for (String permission : mPermissionList) {
                    if (ContextCompat.checkSelfPermission(GuideActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                        // 提示用户应该去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                        break;
                    }
                }
            }
        }
    }

    /**
     * activity加载完成后再弹窗
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        if (hasFocus && isFirst) {
            mPermissionList.clear();
            //判断Android版本是否大于23
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查权限是否已经获取
                for (String permission : permissions) {
                    if (RomUtils.isOppo() || RomUtils.isVivo()) {
                        switch (permission) {
                            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                                if (!writePermission()) {
                                    mPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                }
                                break;
                            case Manifest.permission.CAMERA:
                                if (!cameraPermission()) {
                                    mPermissionList.add(Manifest.permission.CAMERA);
                                }
                                break;
                            case Manifest.permission.ACCESS_COARSE_LOCATION:
                                if (!locationPermission()) {
                                    mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                                }
                                break;
                        }
                    } else {
                        if (!selfPermissionGranted(permission)) {
                            mPermissionList.add(permission);
                        }
                    }
                }
            } else {
                for (String permission : permissions) {
                    switch (permission) {
                        case Manifest.permission.ACCESS_COARSE_LOCATION:
                            if (!locationPermission()) {
                                mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                            }
                            break;
                    }
                }
//                for (String permission : permissions) {
//                    if (!checkPermissionGranted(permission)) {
//                        mPermissionList.add(permission);
//                    }
//                }
            }
            if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            } else {//请求权限方法
                if (RomUtils.isOppo() || RomUtils.isVivo()) {
                    // 提示用户去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
//                String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
//                ActivityCompat.requestPermissions(GuideActivity.this, permissions, 123);
                } else {
                    String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
                    ActivityCompat.requestPermissions(GuideActivity.this, permissions, 123);
                }
            }
            isFirst = false;
        }
    }

    class GuideAdapter extends PagerAdapter
    {
        //item的个数
        @Override
        public int getCount()
        {
            return mImageViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }

        //初始化item布局
        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            ImageView view = mImageViewList.get(position);
            container.addView(view);
            return view;
        }

        //销毁item
        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView((View) object);
        }
    }

    protected void initData()
    {
        mImageViewList = new ArrayList<>();
        for (int i = 0; i < mImageIds.length; i++) {
            //创建ImageView把mImgaeViewIds放进去
            ImageView view = new ImageView(this);
            view.setImageResource(mImageIds[i]);
//            view.setBackgroundResource(mImageIds[i]);
            view.setScaleType(ImageView.ScaleType.CENTER);
            //添加到ImageView的集合中
            mImageViewList.add(view);
            //小圆点
            ImageView pointView = new ImageView(this);
            pointView.setImageResource(R.drawable.shape_guide_point1);
            //初始化布局参数，父控件是谁，就初始化谁的布局参数
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            if (i > 0) {
                //当添加的小圆点的个数超过一个的时候就设置当前小圆点的左边距为10dp;
                params.leftMargin = DeviceInfo.dip2px(this, 10);
            }
            //设置小圆点的宽高包裹内容
            pointView.setLayoutParams(params);
            //将小圆点添加到LinearLayout中
            llContainer.addView(pointView);
            if (i == 2) {//再加一个点
                ImageView pointView2 = new ImageView(this);
                pointView2.setImageResource(R.drawable.shape_guide_point1);
                LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                if (i > 0) {
                    params2.leftMargin = DeviceInfo.dip2px(this, 10);
                }
                pointView2.setLayoutParams(params2);
                llContainer.addView(pointView2);
            }
        }
    }
}
